package helen.core.tools.appmonitor;

import android.util.Log;



import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import helen.core.tools.utils.FileUtils;

/**
 * 用于保存系统时间并且打印相应的系统事件
 * Created by cssnote on 2015/11/2.
 */
public class EventLog {
    private static EventLog eventLog = null;
    private List<Event> eventList;

    private EventLog(){
        eventList = new ArrayList<>();
    }

    public static EventLog GetInstance (){
        if(eventLog == null){
            eventLog = new EventLog();
        }
        return eventLog;
    }

    private class Event {
        public String tag;
        public String time;
        public String event;
    }

    public void PushEvent(String tag,String event){
        if(!MonitorControl.EVENT_LOG){
            return;
        }
        Event eventx = new Event();
        eventx.event = event;
        eventx.time = getTime();
        eventx.tag = tag;
        eventList.add(eventx);
        Log.i(tag, event);
    }

    public void clean(){
        eventList.clear();
    }

    public void printLog(String path,String fileName){
        if(!MonitorControl.APP_MOMITOR){
            return;
        }
        if(fileName == null){
            Calendar ca = Calendar.getInstance();
            fileName = "event_log_";
            fileName += ca.get(Calendar.YEAR)+"-"+ca.get(Calendar.MONTH)+"-"+ca.get(Calendar.DATE)+"_";
            fileName += ca.get(Calendar.HOUR)+":"+ca.get(Calendar.MINUTE)+":"+ca.get(Calendar.SECOND)+".txt";
        }
        FileUtils fileUtils = new FileUtils();
        fileUtils.createSdDir(path);
        String log = "";
        for(int i=0;i<eventList.size();i++){
            log += "["+i+"]:\n";
            log += "tag:"+eventList.get(i).tag+"\n";
            log += "time:"+eventList.get(i).time+"\n";
            log += "event:"+eventList.get(i).event+"\n\n";
        }
        fileUtils.write2SdFromInput(path, fileName, fileUtils.String2InputStream(log));
    }

    public String getLog(){
        if(!MonitorControl.APP_MOMITOR){
            return "";
        }
        String log = "";
        for(int i=0;i<eventList.size();i++){
            log += "["+i+"]:\n";
            log += "tag:"+eventList.get(i).tag+"\n";
            log += "time:"+eventList.get(i).time+"\n";
            log += "event:"+eventList.get(i).event+"\n\n";
        }
        return log;
    }

    private String getTime(){
        String time = "" ;
        Calendar calendar = Calendar.getInstance();
        time += calendar.get(Calendar.YEAR)+"-"+calendar.get(Calendar.MONTH)+"-"+calendar.get(Calendar.DATE)+"_";
        time += calendar.get(Calendar.HOUR)+":"+calendar.get(Calendar.MINUTE)+":"+calendar.get(Calendar.SECOND);
        return time;
    }
}
